package com.itheima.reggie.exception;

import com.itheima.reggie.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


@RestControllerAdvice
public class GlobalExceptionHandler {
    
    

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLException(SQLIntegrityConstraintViolationException e){
        
        //1. 获取异常的信息
        String message = e.getMessage();
        
        //2. 判断是否包含重复性的约束
        if(message.contains("Duplicate entry")){
            String msg = message.split(" ")[2];
            return R.error(msg + "已存在！");
        }
        
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e){
        return R.error(e.getMessage());
    }
}
